Inheritance means extending the properties of one class by another. Inheritance implies code reusability, because of which client classes do not need to implement everything from scratch. They can simply refer to their base classes to execute the code.
Unlike Java
and C#
, like C++
, Python
allows Multiple inheritance. Name resolution is done by the order in which the base classes are specified.
class ClassName(BaseClass1[,BaseClass2,....,BaseClassN]):
<statement 0>
<statement 1>
<statement 2>
...
...
...
<statement n>
In [3]:
class Person:
# Constructor
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return 'name = {}\nage = {}'.format(self.name,self.age)
# Inherited or Sub class
class Employee(Person):
def __init__(self, name, age, employee_id):
Person.__init__(self, name, age) # Referring Base class
# Can also be done by super(Employee, self).__init__(name, age)
self.employee_id = employee_id
# Overriding implied code reusability
def __str__(self):
return Person.__str__(self) + '\nemployee id = {}'.format(self.employee_id)
In [4]:
s = Person('Kiran',18)
print(s)
In [6]:
e = Employee('Ramesh',18,48)
print(e)
In [7]:
class Base1:
def some_method(self):
print('Base1')
class Base2:
def some_method(self):
print('Base2')
class Derived1(Base1,Base2):
pass
class Derived2(Base2,Base1):
pass
Note how pass
statement is used to leave the class body empty. Otherwise it would have raised a Syntax Error. Since Drived1
and Derived2
are empty, they would have imported the methods from their base classes
In [8]:
d1 = Derived1()
d2 = Derived2()
Now what will be the result of invoking some_method
on d1
and d2
? ... Does the name clash ocuur? ... Let's see
In [9]:
d1.some_method()
In [10]:
d2.some_method()
Wow! ... It executed smoothly ...
If a name of a function is same in base classes, the one will be executed, which appears first in the base class list